package com.zkingsoft.actions.visitor;

import java.io.File;
import java.io.FileInputStream;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.zkingsoft.actions.common.BaseController;
import com.zkingsoft.model.AppInterface;
import com.zkingsoft.model.InterfaceCate;
import com.zkingsoft.model.Project;
import com.zkingsoft.plugin.util.LogUtil;
import com.zkingsoft.plugin.util.WebUtil;
import com.zkingsoft.pojo.AjaxResult;
import com.zkingsoft.services.AppInterfaceService;
import com.zkingsoft.services.InterfaceCateService;
import com.zkingsoft.services.ProjectService;
import com.zkingsoft.services.RoleService;
import com.zkingsoft.services.UsersService;

import freemarker.template.Template;

/**
 * @description 企业管理员管理action
 * @author 姜友瑶
 * @email 935090232@qq.com
 * @date 2016-06-26
 */
@Scope("prototype")
@Controller
@RequestMapping(value = "interface")
public class InterfaceController extends BaseController {

	@Resource
	private UsersService currentService;
	@Resource
	private RoleService roleService;
	@Resource
	private InterfaceCateService interfaceCateService;
	@Resource
	private ProjectService projectService;
	@Resource
	private AppInterfaceService appInterfaceService;

	@RequestMapping(value = "/redirect/{page1}/{page2}")
	public String redirect(@PathVariable("page1") String page1, @PathVariable("page2") String page2) {
		return "interface/" + page1 + "/" + page2;
	}

	@RequestMapping(value = "/redirect/{page1}")
	public String redirect(@PathVariable("page1") String page1) {
		return "interface/" + page1;
	}

	@RequestMapping(value = "/welcome")
	public String showListIndex() {
		WebUtil.getRequest().setAttribute("projList", projectService.findByModel(null));
		return "/interface/welcome";
	}

	/**
	 * 进入列表页面
	 */
	@RequestMapping(value = "/goList")
	public String goList(Long id) {
		WebUtil.getSession().setAttribute("projId", id);
		WebUtil.getSession().setAttribute("proj", projectService.findById(id));
		return "interface/interface-list";
	}

	/**
	 * 查询项目中所有的分类
	 */
	@RequestMapping(value = "/interfaceCate/all")
	public @ResponseBody AjaxResult showList(InterfaceCate interfaceCate) {
		if (interfaceCate.getProjId() != null) {
			return new AjaxResult(AjaxResult.STATUS_OK, null, null, interfaceCateService.findByModel(interfaceCate), 0);
		}
		return new AjaxResult(AjaxResult.STATUS_OK, "项目id为null", null, null, 0);
	}

	@RequestMapping(value = "/interfaceCate/findById")
	public @ResponseBody AjaxResult findById(Long id) {
		InterfaceCate interfaceCate = super.findById(interfaceCateService, id);
		return new AjaxResult(AjaxResult.STATUS_OK, null, null, Arrays.asList(interfaceCate), 0);
	}

	@RequestMapping(value = "/interface/fidndAppInterFaceByCate")
	public @ResponseBody AjaxResult fidndAppInterFaceByCate(AppInterface appInterface) {
		return new AjaxResult(AjaxResult.STATUS_OK, null, null, appInterfaceService.selectByModelNoLimit(appInterface),
				0);
	}

	/**
	 * @Description: 方法描述
	 * @author:姜友瑶
	 * @param appInterface
	 * @return 返回类型 AjaxResult
	 * @date 2016年9月11日
	 */
	@RequestMapping(value = "/showInterface")
	public String showInterface(AppInterface appInterface) {
		appInterface = appInterfaceService.findById(appInterface.getId());
		WebUtil.getRequest().setAttribute("obj", appInterface);
		Project project = projectService.findById(appInterface.getProjId());
		WebUtil.getRequest().setAttribute("project", project);
		return "/interface/showInterface";
	}

	/**
	 * @Description: 方法描述
	 * @author:姜友瑶
	 * @param appInterface
	 * @return 返回类型 AjaxResult
	 * @date 2016年9月11日
	 */
	@RequestMapping(value = "/getInterface")
	public @ResponseBody AjaxResult getInterface(AppInterface appInterface) {
		appInterface = appInterfaceService.findById(appInterface.getId());

		Object inParam = JSONObject.parse(appInterface.getInParam());
		Object outParam = JSONObject.parse(appInterface.getOutParam());
		
		 AjaxResult res= new AjaxResult();
		 res.setStatus(AjaxResult.STATUS_OK);
		 res.putInMap("inParam", inParam);
		 res.putInMap("outParam", outParam);
		return res;
	}

	@RequestMapping(value = "/testInterface")
	public String testInterface(AppInterface appInterface) {
		WebUtil.getRequest().setAttribute("obj", appInterfaceService.findById(appInterface.getId()));
		return "/interface/testInterface";
	}

	@RequestMapping(value = "/searchInterface")
	public String searchInterface(AppInterface appInterface) {
		if (appInterface.getName() != null && !appInterface.getName().equals("")) {
			WebUtil.getRequest().setAttribute("list", appInterfaceService.selectByModelNoLimit(appInterface));
			WebUtil.getRequest().setAttribute("name", appInterface.getName());
		}
		return "/interface/searchList";
	}

	// 开始生成文件plush
	@RequestMapping(value = "/download")
	public void generatorUp2(HttpServletResponse response, HttpServletRequest request, AppInterface appInterface) {
		try {

			appInterface = appInterfaceService.findById(appInterface.getId());
			WebUtil.getRequest().setAttribute("obj", appInterface);
			Project project = projectService.findById(appInterface.getProjId());
			WebUtil.getRequest().setAttribute("project", project);

			freemarker.template.Configuration cfg = new freemarker.template.Configuration();
			LogUtil.inof(this.getClass(), this.getClass().getResource("/").getPath());
			cfg.setDirectoryForTemplateLoading(
					new File(this.getClass().getResource("/").getPath() + "template" + File.separator + "java"));
			cfg.setEncoding(Locale.SIMPLIFIED_CHINESE, "UTF-8");
			// 生成代码文件
			// 获取模板（index）
			Template template = cfg.getTemplate("inteface.ftl");

			Map<String, Object> root = new HashMap<String, Object>();
			root.put("obj", appInterface);
			root.put("project", project);
			String name = appInterface.getName() + ".html";

			response.setContentType("multipart/form-data");
			response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(name, "UTF-8"));
			template.process(root, response.getWriter());

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) throws Exception {

		FileInputStream f = new FileInputStream(new File(
				"/Users/jiangyouyao/java/projects/xmgl/xmgl-web/src/main/java/com/zkingsoft/actions/visitor/1.json"));
		byte[] b = new byte[1024 * 1024];
		int i = f.read(b);
		String str = new String(b, 0, i);
		System.out.println(str);
		Object j = JSONObject.parse(str);
		System.out.println(j);

	}

}